package top.mcwebsite.playandroid.lib.task

/**
 * Task 接口
 */
interface Task {
    val name: String
    val priority: Int
    val job: Job
    val dispatchMode: DispatchMode
    val dependsOn: List<String>?

    fun cancel()
}

/**
 * Task 默认实现
 */
class DefaultTaskImpl(
    override val name: String = TaskManager.generatedTaskName(),
    override val priority: Int = Constant.DEFAULT_TASK_PRIORITY,
    override val dispatchMode: DispatchMode,
    override val dependsOn: List<String>?,
    override val job: Job,
) : Task {
    override fun cancel() {

    }
}

/**
 * Task Builder
 */
class TaskBuilder(
    var name: String? = null,
    var job: Job? = null,
    var priority: Int = Constant.DEFAULT_TASK_PRIORITY,
    var dispatchMode: DispatchMode = DispatchMode.MAIN,
    var dependsOn: List<String>? = null
) {
    fun build(): DefaultTaskImpl {
        val taskJob = job ?: throw IllegalArgumentException("job must not be null")
        return DefaultTaskImpl(
            name = this.name ?: TaskManager.generatedTaskName(),
            job = taskJob,
            priority = priority,
            dispatchMode = dispatchMode,
            dependsOn = dependsOn
        )
    }
}

fun task(block: TaskBuilder.() -> Unit): Task {
    val taskBuilder = TaskBuilder()
    taskBuilder.apply(block)
    return taskBuilder.build()
}
